package com.szyt.basicframe.service.impl;

import com.szyt.basicframe.service.ICaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements ICaptchaService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 验证码有效期（秒）
    private static final long CAPTCHA_EXPIRATION = 300;

    private static final String redisPrefix="CAPTCHA:";

    // 存储验证码
    public void storeCaptcha(String sessionId, String captchaCode) {
        redisTemplate.opsForValue().set(
                getRedisKey(sessionId),
                captchaCode,
                CAPTCHA_EXPIRATION,
                TimeUnit.SECONDS);
    }

    // 验证验证码
    public boolean validateCaptcha(String sessionId, String userInputCaptcha) {
        String key = getRedisKey(sessionId);
        String storedCaptcha = redisTemplate.opsForValue().get(key);

        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(userInputCaptcha)) {
            // 验证成功后立即删除，防止重复使用
            redisTemplate.delete(key);
            return true;
        }

        return false;
    }

    //生成验证法在redis中存储数据的key
    private String getRedisKey(String sessionId) {
        return redisPrefix + sessionId;
    }
}
